package com.qdy.service.impl;

import com.qdy.repository.BaseNativeSqlRepository;
import com.qdy.service.UserService;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jws.Oneway;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import java.util.Map;

/**
 * Created by qudingyi on 2017/4/25.
 */
@Service
public class UserServiceImpl implements UserService {
    @PersistenceUnit
    private EntityManagerFactory emf;
    private static  final   String USER_VIEW_SQL="select * from user_view";
    @Autowired
    private BaseNativeSqlRepository baseNativeSqlRepository;

    @Override
    public Map<String, Object> getUserView(Long userId) {
        EntityManager em=emf.createEntityManager();
        Query query=em.createNativeQuery(USER_VIEW_SQL+"   where id=:id");
        query.setParameter("id",userId);
        query.unwrap(org.hibernate.SQLQuery.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

        Map<String,Object> ob = (Map<String,Object>) query.getSingleResult();
        em.close();
        return  ob;
    }

    @Override
    public Map<String, Object> getUserViewByOpenId(String openId) {
        EntityManager em=emf.createEntityManager();
        Query query=em.createNativeQuery(USER_VIEW_SQL+"   where openId=:openId");
        query.setParameter("openId",openId);
        query.unwrap(org.hibernate.SQLQuery.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

        Map<String,Object> ob = (Map<String,Object>) query.getSingleResult();
        em.close();
        return  ob;
    }
}
